// MGisDoc.cpp : implementation of the CMGisDoc class
//

#include "stdafx.h"
#include "MGis.h"

#include "MGisDoc.h"
#include "VectorLayer.h"
#include "Canvas.h"
#include "GISApplication.h"
#include "MapLayerMgr.h"
#include "VectorDataProvider.h"
#include "Map2ClientTransform.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CMGisDoc

IMPLEMENT_DYNCREATE(CMGisDoc, CDocument)

BEGIN_MESSAGE_MAP(CMGisDoc, CDocument)
	ON_COMMAND(ID_FILE_OPEN, &CMGisDoc::OnFileOpen)
END_MESSAGE_MAP()


// CMGisDoc construction/destruction

CMGisDoc::CMGisDoc()
{
	// TODO: add one-time construction code here
	TCHAR exeFullPath[MAX_PATH]; // MAX_PATH
	GetModuleFileName(NULL,exeFullPath,MAX_PATH);

	TCHAR drive[_MAX_DRIVE];
	TCHAR dir[_MAX_DIR];

	_splitpath(exeFullPath, drive, dir, NULL,NULL);
	CString appDirectory;
    appDirectory.Format("%s%s", drive, dir);
    m_pGISApplication = new CGISApplication();
    m_pGISApplication->setApplicationDirectory(appDirectory);
}

CMGisDoc::~CMGisDoc()
{
	if (m_pGISApplication)
	{
		delete m_pGISApplication;
	}
}

BOOL CMGisDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	// TODO: add reinitialization code here
	// (SDI documents will reuse this document)

	return TRUE;
}


// CMGisDoc serialization

void CMGisDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: add storing code here
	}
	else
	{
		// TODO: add loading code here
	}
}


// CMGisDoc diagnostics

#ifdef _DEBUG
void CMGisDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CMGisDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG


// CMGisDoc commands

void CMGisDoc::OnFileOpen()
{
	// TODO: Add your command handler code here
	CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,"Shape Files (*.shp)|*.shp|All Files (*.*)|*.*|");
	if (dlg.DoModal() == IDOK)
	{
		addLayer(dlg.GetPathName());
	}
	this->UpdateAllViews(NULL);
}

void CMGisDoc::addLayer(CString filePath)
{
	TCHAR* szRs = new TCHAR[filePath.GetLength()];
	lstrcpy(szRs, filePath.GetBuffer(filePath.GetLength())); 
	filePath.ReleaseBuffer(); 
	CVectorDataProvider dataProvider(szRs);
	CVectorLayer* layer = dataProvider.createVectorLayer();
	m_pGISApplication->getMapLayerMgr()->addMapLayer(layer);    
	if (m_pGISApplication->getMapLayerMgr()->getMayLayerCount() == 1)
	{
		m_pGISApplication->getCanvas()->getTransform()->setDestCRS(layer->getLayerCRS());
		m_pGISApplication->getCanvas()->setMapExtend(m_pGISApplication->getMapLayerMgr()->getMaxEnvelope());
	}
	else
	{
		CMapLayerEnvelope maxEnvelope = m_pGISApplication->getMapLayerMgr()->getMaxEnvelope();
		maxEnvelope.unionEnvelope(&layer->getLayerEnvelope());
		m_pGISApplication->getCanvas()->setMaxMapExtend(maxEnvelope);
	}
    //delete [] szRs;
}
